/* eslint-disable no-use-before-define */
/* eslint-disable max-len */
import { Ref, computed, ref, SetupContext } from 'vue';
import { TreeViewProps } from '../../tree-view.props';
import { TreeNodeCellMode, VisualTreeNode, VisualTreeNodeCell } from '../../composition/types';
import { cloneDeep } from 'lodash';
import { useTreeNodeIcon } from '../../composition/use-tree-node-icon';
import { useTreeNodeLines } from '../../composition/use-tree-node-lines';
import { useAutoCheckChildrenAndCascade } from '../../composition/use-auto-check-children-and-cascade';

/** 渲染树状区域 */
export default function (props: TreeViewProps, context: SetupContext, treeNodeIconsData: Ref<any>, visibleDatas: Ref<any>) {
    const styleObject = {} as Record<string, any>;
    const treeDataStyle = computed(() => {
        return styleObject;
    });
    /** 选中值 */
    let outputValue: any;
    /** 视图节点数据 */
    const visibleDatasRef = ref(visibleDatas);
    /** 单元格高度 */
    const customCellHeight = ref(props.cellHeight);
    /** 记录最大值 */
    let dictTree = generateDictTree(visibleDatasRef.value);
    /** 记录叶子节点 */
    let leafNodes = getLeafNodes(dictTree);
    /** 记录最大值 */
    let maxLayer = 0;
    /** 获取树节点的最大层级 */
    visibleDatasRef.value.map((visualDataRow: VisualTreeNode) => {
        maxLayer = maxLayer > visualDataRow.layer ? maxLayer : visualDataRow.layer;
    });

    const useTreeNodeIconComposition = useTreeNodeIcon(props, treeNodeIconsData);
    const { treeNodeIconsClass } = useTreeNodeIconComposition;

    const useTreeNodeLinesComposition = useTreeNodeLines(props, visibleDatasRef.value, dictTree);
    const { getPaddingBottomLength, handlePaddingBottomReturnValue, handleCollapsedPaddingBottom } = useTreeNodeLinesComposition;

    const useAutoCheckChildrenAndCascadeComposition = useAutoCheckChildrenAndCascade(
        props,
        visibleDatasRef.value,
        dictTree,
        maxLayer,
        context
    );
    const { onClickTreeNodeSelectableCell } = useAutoCheckChildrenAndCascadeComposition;

    /** 检查点击的节点与下一个节点是否同级 */
    function NextNodeLayer(visualTreeNodeCellIndex: number, visualTreeNodeCellLayer: number) {
        /** 点击的子节点的下一个节点 */
        const nextNode = visibleDatasRef.value[visualTreeNodeCellIndex];
        /** 下一个节点的层级*/
        const nextNodeLayer = nextNode.layer;
        /** 当前节点的层级 */
        const curNodeLayer = visualTreeNodeCellLayer;
        /** 毗邻节点的层级关系 */
        let adjacentNode = 'same';
        if (curNodeLayer > nextNodeLayer) {
            adjacentNode = 'non-child';
        } else if (curNodeLayer < nextNodeLayer) {
            adjacentNode = 'child';
        }
        return adjacentNode;
    }

    function treeNodeIconClass(visualTreeNode: VisualTreeNode, visualTreeNodeCell: VisualTreeNodeCell) {
        const visualTreeNodeCellIndex = Number(visualTreeNodeCell.index);
        let adjacentNode = 'same';
        if (visualTreeNodeCellIndex !== visibleDatasRef.value.length) {
            adjacentNode = NextNodeLayer(visualTreeNodeCellIndex, visualTreeNodeCell.layer);
        }
        let styleObject;
        if (adjacentNode !== 'child') {
            styleObject = '';
        } else {
            styleObject = visualTreeNode.collapse
                ? ({ 'fv-tree-node-toggle': true } as Record<string, any>)
                : { 'fv-tree-node-toggle-minus': true };
        }
        return styleObject;
    }

    /** 返回叶子节点的值 */
    function getLeafNodes(dictTreeValue: any) {
        const leafNodes: any = [];
        for (let i = 1; i < dictTreeValue.length; i++) {
            if (dictTreeValue[i].childs.length === 0) {
                leafNodes.push(i.toString());
            }
        }
        return leafNodes;
    }

    /** 生成树节点的唯一键值 */
    function treeNodeKey(visualTreeNode: VisualTreeNode): string {
        return `r_${visualTreeNode.index}_${visualTreeNode.refreshKey || ''}`;
    }

    /** 生成树节点单元格的唯一键值 */
    function treeNodeCellKey(visualTreeNode: VisualTreeNode, cellIndex: number): string {
        return `r_${visualTreeNode.index}_c_${cellIndex}_${visualTreeNode.refreshKey || ''}`;
    }

    /** 生成树节点的 CSS 类 */
    function treeNodeClass(visualTreeNode: VisualTreeNode): Record<string, boolean> {
        const classObject = {
            'fv-tree-node': true,
            selected: visualTreeNode.selected
        } as Record<string, boolean>;
        return classObject;
    }

    /** 生成树节点的位置样式 */
    function treeNodePosition(visualTreeNode: VisualTreeNode): Record<string, any> {
        const rowHeight = visualTreeNode.height ? `${visualTreeNode.height}px` : '';
        const styleObject = visualTreeNode.show
            ? ({
                top: `${visualTreeNode.top}px`,
                height: `${rowHeight}`
            } as Record<string, any>)
            : {
                display: 'none'
            };
        return styleObject;
    }

    /** 重新计算收折后的高度 */
    function resetTreeNodePosition() {
        const height = visibleDatasRef.value[1].top;
        let curTop = visibleDatasRef.value[0].top;
        for (let i = 1; i < visibleDatasRef.value.length; i++) {
            if (visibleDatasRef.value[i].show) {
                curTop += height;
                visibleDatasRef.value[i].top = curTop;
            }
        }
        return visibleDatasRef.value;
    }

    /** 生成树节点单元格的位置样式 */
    function treeNodeCellPosition(visualTreeNode: VisualTreeNode): Record<string, any> {
        const visualTreeNodeCell = visualTreeNode.data.displayText;
        const cellHeight = visualTreeNodeCell.layer.height ? `${visualTreeNodeCell.layer.height}px` : '';
        const styleObject = visualTreeNode.show
            ? ({
                height: `${cellHeight}`,
                left: `${visualTreeNodeCell.layer * 20}px`,
                paddingBottom: handlePaddingBottomReturnValue(visualTreeNodeCell.index, leafNodes, dictTree, visibleDatasRef.value),
                background: getPaddingBottomLength(visualTreeNodeCell.index, dictTree)
            } as Record<string, any>)
            : {
                display: 'none'
            };
        styleObject.lineHeight = `${customCellHeight.value}px`;
        return styleObject;
    }

    /**  处理树节点鼠标悬停事件 */
    function onMouseoverTreeNode(e: MouseEvent, visualTreeNode: VisualTreeNode) {}
    function onclickTreeNode(e: any, visualTreeNode: VisualTreeNode) {
        visualTreeNode.selected = true;
        context.emit('outputValue', visualTreeNode);
        context.emit('currentEvent', e);

        visibleDatasRef.value.forEach((visibleDatasItem: any) => {
            visibleDatasItem.selected = visibleDatasItem.index === visualTreeNode.index;
        });
    }

    /** 处理子节点部分折叠的情况,跳过折叠的子节点
     * @param i 点击的节点的index
     */
    function partiallyCollapseStatus(curIndex: number, visibleDatasValue: any) {
        const visibleDatasItemLayer = visibleDatasValue[curIndex].layer;
        let i = curIndex + 1;
        while (i < visibleDatasValue.length) {
            if (visibleDatasValue[i].layer > visibleDatasItemLayer) {
                i++;
            } else {
                break;
            }
        }
        return i - 1;
    }

    /** 处理选择的节点的子节点
     * @param id 选中节点的index，即id
     * @param parentIdOfCurNode 选中节点的父级id
     */
    function onSelectedTreeNodeChild(id: number, parentIdOfCurNode: number) {
        // 选中节点的折叠状态改变
        visibleDatasRef.value[id - 1].collapse = !visibleDatasRef.value[id - 1].collapse;
        /** 选中节点的折叠状态 */
        const curNodeCollapseStatus = visibleDatasRef.value[id - 1].collapse;
        /** 开关，判断是否开始切换为非子节点，若不是，则为true */
        let switchForTreeNodes = false;
        // 从当前节点索引开始往后比较
        let i = id - 1;
        while (i < visibleDatasRef.value.length) {
            /** 每个节点 */
            const visibleDatasItem = visibleDatasRef.value[i] as any;
            /** 每个节点的父级Id */
            const visibleDatasItemParentId = Number(visibleDatasItem.data.displayText.parentId);
            // 判断是否为选中节点的子节点
            if (visibleDatasItemParentId > parentIdOfCurNode) {
                // 选中节点的子节点，及子节点的子节点等，都需要修改显示状态
                visibleDatasItem.show = !curNodeCollapseStatus;
                if (visibleDatasItem.collapse) {
                    i = partiallyCollapseStatus(i, visibleDatasRef.value);
                }
                switchForTreeNodes = true;
            } else if (switchForTreeNodes) {
                i++;
                break;
            }
            i++;
        }
        return visibleDatasRef.value;
    }

    /**  处理树节点单元格点击事件 */
    function onClickTreeNodeCell(visualTreeNodeCell: VisualTreeNodeCell) {
        const visualTreeNodeCellIndex = Number(visualTreeNodeCell.index);
        let adjacentNode = 'same';
        if (visualTreeNodeCellIndex !== visibleDatasRef.value.length) {
            adjacentNode = NextNodeLayer(visualTreeNodeCellIndex, visualTreeNodeCell.layer);
        }
        if (adjacentNode === 'child') {
            visibleDatasRef.value = onSelectedTreeNodeChild(visualTreeNodeCellIndex, Number(visualTreeNodeCell.parentId));
        }
        resetTreeNodePosition();
        visibleDatas = handleCollapsedPaddingBottom(visualTreeNodeCell.index, visibleDatasRef.value, leafNodes, dictTree);
    }
    /** 标签样式 */
    function getLabelStyle() {
        const styleObject = {
            minHeight: `${customCellHeight.value}px`,
            marginBottom: '0'
        } as Record<string, any>;
        return styleObject;
    }

    /** 渲染树节点 */
    function renderTreeNode(visualTreeNode: VisualTreeNode, dictTree: any, leafNodes: any) {
        return (
            <div
                ref={visualTreeNode.setRef}
                key={treeNodeKey(visualTreeNode)}
                class={treeNodeClass(visualTreeNode)}
                style={treeNodePosition(visualTreeNode)}
                onMouseover={(payload: MouseEvent) => onMouseoverTreeNode(payload, visualTreeNode)}
                onClick={(payload: MouseEvent) => onclickTreeNode(payload, visualTreeNode)}>
                {Object.values(visualTreeNode.data).map((cell: VisualTreeNodeCell) => {
                    return (
                        <>
                            <div
                                ref={cell.setRef}
                                key={treeNodeCellKey(visualTreeNode, cell.index)}
                                class="fv-tree-node-cell"
                                style={treeNodeCellPosition(visualTreeNode)}>
                                <div class={treeNodeIconClass(visualTreeNode, cell)} onClick={() => onClickTreeNodeCell(cell)}></div>
                                {treeNodeIconsData.value.fold && props.showTreeNodeIcons ? (
                                    <div id="treeNodeIcons" class={treeNodeIconsClass(visualTreeNode, cell, leafNodes)}></div>
                                ) : (
                                    ''
                                )}
                                {props.selectable ? (
                                    <>
                                        <input type="checkbox"></input>
                                        <label
                                            style={getLabelStyle()}
                                            onClick={(payload: MouseEvent) =>
                                                onClickTreeNodeSelectableCell(payload, visualTreeNode, cell, dictTree)
                                            }></label>
                                    </>
                                ) : (
                                    ''
                                )}
                                <span title={cell.data}>{cell.mode === TreeNodeCellMode.editing ? cell.getEditor(cell) : cell.data}</span>
                            </div>
                        </>
                    );
                })}
            </div>
        );
    }

    /** 处理树字典的父级 */
    function handleDictTreeParents(dictTreeValue: any) {
        for (let i = 1; i < dictTreeValue.length; i++) {
            if (dictTreeValue[i]) {
                if (dictTreeValue[i].childs) {
                    for (let m = 0; m < dictTreeValue[i].childs.length; m++) {
                        const child = dictTreeValue[i].childs[m];
                        if (dictTreeValue[child]) {
                            if (dictTreeValue[i].parents) {
                                dictTreeValue[child].parents = cloneDeep(dictTreeValue[i].parents);
                            }
                            dictTreeValue[child].parents.push(i.toString());
                        }
                    }
                }
            }
        }
        return dictTreeValue;
    }

    /** 去重 */
    function delMutipleValue(dictTreeValue: any) {
        dictTreeValue.forEach((dictTreeItem: any) => {
            const uniqueSet = new Set(dictTreeItem.childs);
            const outputArray = [...uniqueSet];
            dictTreeItem.childs = outputArray.sort((a, b) => Number(a) - Number(b));
        });
    }

    /** 处理树字典的子级 */
    function handleDictTreeChilds(dictTreeValue: any) {
        if (dictTreeValue) {
            for (let i = 1; i < dictTreeValue.length; i++) {
                if (dictTreeValue[i].childs) {
                    dictTreeValue[i].parents.forEach((parent: string) => {
                        dictTreeValue[parent].childs.push(i.toString());
                    });
                }
            }
            delMutipleValue(dictTreeValue);
        }
        return dictTreeValue;
    }

    /** 处理树字典的子级展示线长 */
    function handleChildWithLines(dictTreeValue: any) {
        if (dictTreeValue) {
            for (let i = 0; i < dictTreeValue.length; i++) {
                /** 该节点的临近子节点 */
                const neighborChild = dictTreeValue[i].neighborChilds;
                // 若并非只有一个临近子节点
                if (neighborChild.length >= 2) {
                    dictTreeValue[i].childWithLines = [];
                    let childsLength = neighborChild.length - 2;
                    for (let m = 0; m < neighborChild.length - 1; m++) {
                        // 共有多少子节点（去掉最后的子节点的高度）
                        childsLength += dictTreeValue[neighborChild[m]].childs.length;
                        dictTreeValue[i].childWithLines.push(...dictTreeValue[neighborChild[m]].childs, neighborChild[m]);
                    }
                    dictTreeValue[i].childsLength = childsLength;
                }
            }
        }
        return dictTreeValue;
    }

    /** 根据父子级关系，生成对应的index数组 */
    function generateDictTree(visibleDatasValue: VisualTreeNode[]) {
        let dictTreeValue = [];
        let dictTreeItem: any = {
            name: '',
            parents: [],
            childs: [],
            neighborParentId: '',
            neighborChilds: [],
            childWithLines: []
        };
        // 确保编号从1开始；
        dictTreeValue.push(cloneDeep(dictTreeItem));
        for (let x = 0; x < visibleDatasValue.length; x++) {
            const curIndex = visibleDatasValue[x].data.displayText.index;
            const curParentId = visibleDatasValue[x].data.displayText.parentId;
            const name = visibleDatasValue[x].data.displayText.data;
            dictTreeItem.name = name;
            dictTreeItem.neighborParentId = curParentId || '';
            for (let y = 0; y < visibleDatasValue.length; y++) {
                // 首个节点index为1，parent为'';第二个节点index为2，parent为1
                const childIndex = visibleDatasValue[y].data.displayText.index;
                const childParentId = visibleDatasValue[y].data.displayText.parentId;
                // 处理首个节点逻辑
                if (curParentId === '') {
                    // 处理parent
                    dictTreeItem.parents = [];
                    // 处理child
                    if (childParentId === curIndex) {
                        dictTreeItem.childs.push(childIndex);
                        dictTreeItem.neighborChilds.push(childIndex);
                    }
                }
                // 处理其他节点的逻辑——处理child
                else if (childParentId === curIndex) {
                    dictTreeItem.childs.push(childIndex);
                    dictTreeItem.neighborChilds.push(childIndex);
                }
            }
            dictTreeValue[x + 1] = cloneDeep(dictTreeItem);
            dictTreeItem = {
                name: '',
                parents: [],
                childs: [],
                neighborParentId: '',
                neighborChilds: [],
                childWithLines: []
            };
        }
        dictTreeValue = handleDictTreeParents(dictTreeValue);
        dictTreeValue = handleDictTreeChilds(dictTreeValue);
        if (props.showLines) {
            dictTreeValue = handleChildWithLines(dictTreeValue);
        }
        return dictTreeValue;
    }

    /** 渲染树状视图的数据区域 */
    function renderTreeData() {
        dictTree = generateDictTree(visibleDatasRef.value);
        leafNodes = getLeafNodes(dictTree);
        return visibleDatasRef.value.map((visualDataRow: VisualTreeNode) => {
            return renderTreeNode(visualDataRow, dictTree, leafNodes);
        });
    }

    /** 渲染树状视图的整个区域，包括数据区域 */
    function renderTreeArea() {
        return (
            <div class="fv-tree-data" style={treeDataStyle.value}>
                {renderTreeData()}
            </div>
        );
    }

    return {
        renderTreeArea,
        dictTree
    };
}
